package com.qdaily.ui.ui.views;

import android.content.Context;
import android.content.res.TypedArray;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.*;

import com.qdaily.supportlibrary.pulltorefresh.PtrDefaultHandler;
import com.qdaily.supportlibrary.pulltorefresh.PtrFrameLayout;
import com.qdaily.supportlibrary.pulltorefresh.PtrHandler;
import com.qdaily.supportlibrary.pulltorefresh.PtrUIRefreshCompleteHandler;
import com.qdaily.supportlibrary.pulltorefresh.header.RentalsSunHeaderView;
import com.qdaily.supportlibrary.pulltorefresh.loadmore.LoadMoreContainer;
import com.qdaily.supportlibrary.pulltorefresh.loadmore.LoadMoreHandler;
import com.qdaily.supportlibrary.pulltorefresh.loadmore.LoadMoreListViewContainer;
import com.qdaily.supportlibrary.util.LocalDisplay;
import com.qdaily.ui.R;

/**
 * 统一对上下拉刷新的封装。
 * Created with IntelliJ IDEA.
 * User: Felix
 * Date: 4/8/15
 * Time: 13:16
 * QQ:74104
 * Email:lovejiuwei@gmail.com
 */
public class QDRefreshListView extends PtrFrameLayout {
    private ListView mListView;
    private OnRefreshAndLoadMoreListener onRefreshAndLoadMoreListener;
    private LoadMoreListViewContainer loadMoreListViewContainer;
    private RentalsSunHeaderView header;

    private boolean isShowHeadRefreshView;
    private boolean isShowLoadMoreView;
    private boolean isAutoRefresh;

    public QDRefreshListView(Context context) {
        this(context, null);
    }

    public QDRefreshListView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public QDRefreshListView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        parseAttributes(context.obtainStyledAttributes(attrs, R.styleable.QDRefreshListView));
        initViewRes();
    }

    private void initViewRes() {
        View view = LayoutInflater.from(getContext()).inflate(R.layout.view_refreshandloadmorelistview, null);
        this.addView(view);
        initViewRes(view);
    }

    private void initViewRes(View view) {
        mListView = (ListView) view.findViewById(R.id.loadMoreListView);
        mListView.setVerticalScrollBarEnabled(false);

        if (isShowHeadRefreshView) {
            header = new RentalsSunHeaderView(getContext());
            header.setPadding(0, LocalDisplay.dp2px(15), 0, LocalDisplay.dp2px(15));
            this.setHeaderView(header);
            this.addPtrUIHandler(header);
            this.setLoadingMinTime(1000);
            this.setRatioOfHeaderHeightToRefresh(0.4f);
            this.disableWhenHorizontalMove(true);
        }

        this.setPtrHandler(new PtrHandler() {
            @Override
            public boolean checkCanDoRefresh(PtrFrameLayout frame, View content, View header) {
                return PtrDefaultHandler.checkContentCanBePulledDown(frame, mListView, header);
            }

            @Override
            public void onRefreshBegin(PtrFrameLayout frame) {
                if (onRefreshAndLoadMoreListener != null) {
                    onRefreshAndLoadMoreListener.onRefreshBegin();
                }
            }
        });

        loadMoreListViewContainer = (LoadMoreListViewContainer) view.findViewById(R.id.loadMoreListViewContainer);

        loadMoreListViewContainer.setLoadMoreHandler(new LoadMoreHandler() {
            @Override
            public void onLoadMore(LoadMoreContainer loadMoreContainer) {
                if (onRefreshAndLoadMoreListener != null) {
                    if (isShowLoadMoreView) {
                        if (footView == null) {
                            footView = new QDLoadMoreView(getContext());
                            footView.setLayoutParams(new AbsListView.LayoutParams(AbsListView.LayoutParams.MATCH_PARENT, AbsListView.LayoutParams.WRAP_CONTENT));
                            loadMoreListViewContainer.setLoadMoreView(footView);
                        }
                        footView.setVisibility(VISIBLE);
                        footView.start();
                    }

                    onRefreshAndLoadMoreListener.onLoadMore();
                }
            }
        });

        this.addPtrUIHandler(new PtrUIRefreshCompleteHandler() {
            @Override
            public void onUIRefreshComplete(PtrFrameLayout frame) {
                if (onRefreshAndLoadMoreListener != null) {
                    onRefreshAndLoadMoreListener.onUIRefreshComplete();
                }
            }
        });

        if (isShowLoadMoreView) {
            footView = new QDLoadMoreView(getContext());
            footView.setLayoutParams(new AbsListView.LayoutParams(AbsListView.LayoutParams.MATCH_PARENT, AbsListView.LayoutParams.WRAP_CONTENT));
            loadMoreListViewContainer.setLoadMoreView(footView);
            footView.setVisibility(GONE);
        }
        if (isAutoRefresh)
            setAutoRefresh(false);
    }

    private void parseAttributes(TypedArray a) {
        isShowHeadRefreshView = a.getBoolean(R.styleable.QDRefreshListView_showheadrefreshview, true);
        isShowLoadMoreView = a.getBoolean(R.styleable.QDRefreshListView_showloadmoreview, true);
        isAutoRefresh = a.getBoolean(R.styleable.QDRefreshListView_autorefresh, true);
        a.recycle();
    }

    /**
     * 是否还有下一页数据， 在onUIRefreshComplete调用，切记。
     */
    private QDLoadMoreView footView;

    public void hasMoreLoadData(boolean emptyResult, boolean hasMore) {
        loadMoreListViewContainer.loadMoreFinish(emptyResult, hasMore);

        if (!hasMore) {
            if (footView != null) {

                footView.setVisibility(GONE);
                loadMoreListViewContainer.removeFooterView(footView);
                footView.stop();
                footView = null;
            }
        } else {
            if (footView != null) {
                footView.pause();
            }
        }
    }

    /**
     * 设置为空界面
     *
     * @param emptyView
     */
    public void setEmptyView(final View emptyView) {
        if (mListView != null) {
            LinearLayout.LayoutParams ll = new LinearLayout.LayoutParams(-1, -1);
            mListView.setLayoutParams(ll);
            ((ViewGroup) mListView.getParent()).addView(emptyView);
            mListView.setEmptyView(emptyView);
        }
    }

    /**
     * 设置条目点击事件
     *
     * @param onItemClickListener
     */
    public void setOnItemClick(AdapterView.OnItemClickListener onItemClickListener) {
        if (mListView != null) {
            mListView.setOnItemClickListener(onItemClickListener);
        }
    }

    /**
     * 设置条目长点击事件
     *
     * @param onItemLongClickListener
     */
    public void setOnItemLongClick(AdapterView.OnItemLongClickListener onItemLongClickListener) {
        if (mListView != null) {
            mListView.setOnItemLongClickListener(onItemLongClickListener);
        }
    }

    /**
     * 设置是否自动刷新
     *
     * @param isAutoRefresh
     */
    public void setAutoRefresh(final boolean isAutoRefresh) {
        if (this != null) {
            this.postDelayed(new Runnable() {
                @Override
                public void run() {
                    QDRefreshListView.this.autoRefresh(isAutoRefresh);
                }
            }, 100);
        }
    }

    /**
     * 设置adapter
     *
     * @param adapter
     */
    public void setAdapter(BaseAdapter adapter) {
        if (mListView != null) {
            mListView.setAdapter(adapter);
        }
    }

    public void addHeaderView(View view) {
        if (mListView != null) {
            mListView.addHeaderView(view, null, false);
        }
    }

    /**
     * 设置回调完成
     */
    public void onRefreshComplete() {
        this.refreshComplete();
    }


    public void setOnScrollListener(AbsListView.OnScrollListener o) {
        loadMoreListViewContainer.setOnScrollListener(o);
    }

    public void setOnTouchListener(OnTouchListener listener) {
        mListView.setOnTouchListener(listener);
    }

    /**
     * 设置回调监听
     *
     * @param onRefreshAndLoadMoreListener
     */
    public void setOnRefreshAndLoadMoreListener(OnRefreshAndLoadMoreListener onRefreshAndLoadMoreListener) {
        this.onRefreshAndLoadMoreListener = onRefreshAndLoadMoreListener;
    }

    public void setSelection(int itemId) {
        mListView.setSelection(itemId);
    }
}
